package com.es.service.impl;


import com.es.service.IndexService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @Author 咕唧
 * @Date 2022/6/21 17:04
 * @Version 1.0
 */
@Service
public class IndexServiceImpl implements IndexService {

    private RestHighLevelClient client;

    @Autowired
    public void setClient(RestHighLevelClient client) {
        this.client = client;
    }

    @Override
    public CreateIndexResponse createIndex(String index, CreateIndexRequest createIndexRequest) throws IOException {
        //创建库的对象
//        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        CreateIndexResponse response = null;
        if (!indexExist(index)) {
            response = client.indices()
                    .create(createIndexRequest, RequestOptions.DEFAULT);
        }
        return response;
    }

    @Override
    public boolean indexExist(String index) throws IOException {
        //创建查询库的请求对象
        GetIndexRequest request = new GetIndexRequest(index);
        //判断库是否存在
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }

    @Override
    public AcknowledgedResponse deleteIndex(String index) throws Exception {
        AcknowledgedResponse response=null;
        //存在库，删除
        if (indexExist(index)) {
            DeleteIndexRequest deleteIndexRequest =new DeleteIndexRequest(index);
             response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        }
        return response;
    }

    @Override
    public GetIndexResponse getIndex(String index) throws Exception {
        GetIndexRequest request = new GetIndexRequest(index);
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        Map<String, MappingMetadata> mappings = response.getMappings();
        Map<String, Settings> settings = response.getSettings();
//        System.err.println(response);
        return response;
    }


}
